package com.ruoyi.system.service.impl;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.validation.Validator;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hankcs.hanlp.dictionary.py.Pinyin;
import com.hankcs.hanlp.dictionary.py.PinyinDictionary;
import com.hankcs.hanlp.seg.common.Term;
import com.hankcs.hanlp.tokenizer.NLPTokenizer;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.school.domain.*;
import com.ruoyi.school.domain.dto.ImportDanWeiInfo;
import com.ruoyi.school.domain.dto.ImportStudentInfo;
import com.ruoyi.school.domain.dto.ImportTeacherInfo;
import com.ruoyi.school.service.*;
import com.ruoyi.system.enums.CityCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysPost;
import com.ruoyi.system.domain.SysUserPost;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysPostMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    protected Validator validator;

    @Resource
    private StudentService studentService;

    @Resource
    private PacClassService pacClassService;

    @Resource
    private PacFacultiesService pacFacultiesService;

    @Resource
    private PacTeacherService teacherService;

    @Resource
    private RedisCache redisCache;

    @Resource
    private PacDanweiService pacDanweiService;

    @Resource
    private PacActivationStatusService pacActivationStatusService;


    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
//    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        List<SysUser> sysUsers = userMapper.selectUserList(user);

        for (SysUser sysUser : sysUsers) {
            String cacheKey = "sys_user_role_" + sysUser.getUserName();
            // 放入redis
            List<SysRole> cacheList = redisCache.getCacheObject(cacheKey);
            if (cacheList != null) {
                sysUser.setRoles(cacheList);
            } else {
                List<SysRole> sysRoles = roleMapper.selectRolesByUserName(sysUser.getUserName());
                redisCache.setCacheObject(cacheKey, sysRoles, 10, TimeUnit.MINUTES);
                sysUser.setRoles(sysRoles);
            }
        }
        return sysUsers;
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
//    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
//    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 查询用户所属角色组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String userName) {
        List<SysRole> list = roleMapper.selectRolesByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String userName) {
        List<SysPost> list = postMapper.selectPostsByUserName(userName);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkUserNameUnique(user.getUserName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(user);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(user);
        // 清空redis
        String cacheKey = "sys_user_role_" + user.getUserName();
        redisCache.deleteObject(cacheKey);
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 修改用户头像
     *
     * @param userName 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String userName, String avatar) {
        return userMapper.updateUserAvatar(userName, avatar) > 0;
    }

    /**
     * 重置用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetPwd(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 重置用户密码
     *
     * @param userName 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String userName, String password) {
        return userMapper.resetUserPwd(userName, password);
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(SysUser user) {
        this.insertUserRole(user.getUserId(), user.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        // 删除用户与老师的关联
        teacherService.deleteTeacherByUserIds(userIds);
        // 删除用户与学生的关联
        studentService.deleteStudentByUserIds(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUserName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    deptService.checkDeptDataScope(user.getDeptId());
                    String password = configService.selectConfigByKey("sys.user.initPassword");
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    deptService.checkDeptDataScope(user.getDeptId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUserName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUserName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUserName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 根据id，查询用户列表
     *
     * @param userIds
     * @return
     */
    @Override
    public List<SysUser> selectUserListByIds(List<Long> userIds) {
        if (userIds != null && !userIds.isEmpty()) {
            return lambdaQuery().in(SysUser::getUserId, userIds).list();
        }
        return new ArrayList<>();
    }

    /**
     * 导入学生数据
     *
     * @param studentList
     * @param operName
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importStudent(List<ImportStudentInfo> studentList, String operName) {
        if (StringUtils.isNull(studentList) || studentList.size() == 0) {
            throw new ServiceException("导入学生数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        HashMap<String, PacClass> classHashMap = new HashMap<>();
        HashMap<String, PacFaculties> pacFacultiesHashMap = new HashMap<>();
        for (ImportStudentInfo studentInfo : studentList) {
            try {
                Student student = studentService.getOneByStuNum(studentInfo.getStuNum());

                SysUser sysUser = new SysUser();
                sysUser.setSex(Objects.equals(studentInfo.getSex(), "男") ? "0" : Objects.equals(studentInfo.getSex(), "女") ? "1" : "2");
                // 密码姓名首字母小写@学号
                String firstLetterLowercase = getFirstLetterLowercase(studentInfo.getStuName());
                String password = firstLetterLowercase + "@" + studentInfo.getStuNum();
                sysUser.setPassword(SecurityUtils.encryptPassword(password));
                sysUser.setCreateBy(operName);
                sysUser.setUserName(studentInfo.getStuNum());
                sysUser.setNickName(studentInfo.getStuName());
                sysUser.setPhonenumber(studentInfo.getPhone());
                sysUser.setDeptId(103L);
                if(studentInfo.getSex().equals("男")){
                    sysUser.setAvatar("/profile/avatar/2025/07/10/studentMan.jpg");
                }else{
                    sysUser.setAvatar("/profile/avatar/2025/07/10/studentWoman.jpg");
                }
                Student importStudent = new Student();

                if (student != null) {
                    sysUser.setUserId(student.getUserId());
                    importStudent.setId(student.getId());
                }
                // 插入用户信息
                if (sysUser.getUserId() == null) {
                    userMapper.insertUser(sysUser);
                    // 插入学生角色信息
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(sysUser.getUserId());
                    sysUserRole.setRoleId(101L);
                    userRoleMapper.insertUserRole(sysUserRole);
                } else {
                    userMapper.updateUser(sysUser);
                }


                importStudent.setBirth(studentInfo.getBirth());
                importStudent.setUserId(sysUser.getUserId());
                importStudent.setStuName(studentInfo.getStuName());
                importStudent.setStuNum(studentInfo.getStuNum());
                importStudent.setStuFaculties(studentInfo.getFaculties());
                importStudent.setYearEnrollment(studentInfo.getYearEnrollment());
                importStudent.setStuClass(studentInfo.getStuClass());
                importStudent.setMajor(studentInfo.getMajor());
                importStudent.setBigTeam(studentInfo.getBigTeam());
                importStudent.setSmallTeam(studentInfo.getSmallTeam());
                importStudent.setNation(studentInfo.getNation());
                importStudent.setPoliticalOutlook(studentInfo.getPoliticalOutlook());
                importStudent.setStuPlace(studentInfo.getDomicile());
                importStudent.setStuPhone(studentInfo.getPhone());
                importStudent.setStuGradYear(studentInfo.getYearEnrollment() + 4);
                importStudent.setStuCity(studentInfo.getDomicile());

                // 插入院系信息
                if (studentInfo.getFaculties() != null) {
                    PacFaculties pacFaculties = pacFacultiesHashMap.get(studentInfo.getFaculties());
                    if (pacFaculties == null) {
                        pacFaculties = pacFacultiesService.getInfoByFacultiesName(studentInfo.getFaculties());
                    }
                    if (pacFaculties == null) {
                        pacFaculties = new PacFaculties();
                        pacFaculties.setFacultiesName(studentInfo.getFaculties());
                        pacFacultiesService.save(pacFaculties);
                    }
                    importStudent.setFacultiesId(Long.valueOf(pacFaculties.getId()));
                }
                // 根据班级名称 查找 班级信息
                if (studentInfo.getStuClass() != null) {
                    PacClass pacClass = classHashMap.get(studentInfo.getStuClass());
                    if (pacClass == null) {
                        pacClass = pacClassService.getInfoByClassName(studentInfo.getStuClass());
                    }
                    if (pacClass == null) {
                        pacClass = new PacClass();
                        pacClass.setClassName(studentInfo.getStuClass());
                        pacClass.setFacultiesId(importStudent.getFacultiesId().intValue());
                        pacClassService.save(pacClass);
                    }

                    importStudent.setClassId(Long.valueOf(pacClass.getId()));
                }

                // 插入学生信息
                studentService.saveOrUpdate(importStudent);

                successNum++;
                successMsg.append("<br/>" + successNum + "姓名 " + studentInfo.getStuName() + "、学号 " + studentInfo.getStuNum() + " 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "姓名 " + studentInfo.getStuName() + "、学号 " + studentInfo.getStuNum() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 导入老师信息
     *
     * @param teacherInfoList
     * @param operName
     * @return
     */
    @Override
    public String importTeacher(List<ImportTeacherInfo> teacherInfoList, String operName) {
        if (StringUtils.isNull(teacherInfoList) || teacherInfoList.size() == 0) {
            throw new ServiceException("导入教师数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ImportTeacherInfo teacherInfo : teacherInfoList) {
            try {
                PacTeacher teacher = teacherService.getOneByTeaNum(teacherInfo.getTeacherNum());
                // 插入用户数据
                SysUser sysUser = new SysUser();
                if (teacherInfo.getSex().equals("男")) {
                    sysUser.setSex("0");
                } else {
                    sysUser.setSex("1");
                }
                sysUser.setSex(teacherInfo.getSex());
                // 密码姓名首字母小写@学号
                String firstLetterLowercase = getFirstLetterLowercase(teacherInfo.getTeacherName());
                String password = firstLetterLowercase + "@" + teacherInfo.getTeacherNum();
                sysUser.setPassword(SecurityUtils.encryptPassword(password));
                sysUser.setCreateBy(operName);
                sysUser.setUserName(teacherInfo.getTeacherNum());
                sysUser.setNickName(teacherInfo.getTeacherName());
                sysUser.setPhonenumber(teacherInfo.getPhone());
                sysUser.setDeptId(103L);
                if(teacherInfo.getSex().equals("男")){
                    sysUser.setAvatar("/profile/avatar/2025/07/10/teacherMan.jpg");
                }else{
                    sysUser.setAvatar("/profile/avatar/2025/07/10/teacherWoman.jpg");
                }

                // 插入老师信息
                PacTeacher importTeacher = new PacTeacher();

                if (teacher != null) {
                    sysUser.setUserId(Long.valueOf(teacher.getUserId()));
                    importTeacher.setId(teacher.getId());
                }
                // 插入用户信息
                if (sysUser.getUserId() == null) {
                    userMapper.insertUser(sysUser);
                    // 插入老师角色信息
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(sysUser.getUserId());
                    String teacherType = teacherInfo.getTeacherType();
                    List<String> list = Arrays.asList(teacherType.split("、"));
                    if (list.contains("专业教师")) {
                        sysUserRole.setRoleId(105L);
                        userRoleMapper.insertUserRole(sysUserRole);
                    }

                    if (list.contains("学业导师")) {
                        sysUserRole.setRoleId(104L);
                        userRoleMapper.insertUserRole(sysUserRole);
                    }

                    if (list.contains("中队长")) {
                        sysUserRole.setRoleId(103L);
                        userRoleMapper.insertUserRole(sysUserRole);
                    }
                } else {
                    userMapper.updateUser(sysUser);
                }
                importTeacher.setUserId(sysUser.getUserId().intValue());
                importTeacher.setTeacherName(teacherInfo.getTeacherName());
                importTeacher.setTeacherNum(teacherInfo.getTeacherNum());
                importTeacher.setBirth(teacherInfo.getBirth());
                importTeacher.setEducation(teacherInfo.getEducation());
                importTeacher.setDegree(teacherInfo.getDegree());
                importTeacher.setTitle(teacherInfo.getTitle());
                importTeacher.setFaculties(teacherInfo.getFaculties());
                // 插入老师信息
                teacherService.saveOrUpdate(importTeacher);

                successNum++;
                successMsg.append("<br/>" + successNum + "姓名 " + teacherInfo.getTeacherNum() + "工号号 " + teacherInfo.getTeacherNum() + " 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "姓名 " + teacherInfo.getTeacherName() + "、学号 " + teacherInfo.getTeacherNum() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<SysUser> selectByIds(List<Long> userIds) {
        return lambdaQuery().in(SysUser::getUserId, userIds).list();
    }

    /**
     * 导入单位数据
     *
     * @param danWeiInfoList
     * @param operName
     * @return
     */
    @Override
    @Transactional
    public String importDanWei(List<ImportDanWeiInfo> danWeiInfoList, String operName) {
        if (StringUtils.isNull(danWeiInfoList) || danWeiInfoList.size() == 0) {
            throw new ServiceException("导入单位用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ImportDanWeiInfo danWeiInfo : danWeiInfoList) {
            try {
                // 顺序号开始位
                int start = 1;
                // 找到角色位单位的用户的名字
//                SysUser user = userMapper.selectLastDanwei();
                PacActivationStatus pacActivationStatus = pacActivationStatusService.selectByCity(danWeiInfo.getCity());
                if (pacActivationStatus != null) {
                    start = pacActivationStatus.getActivatedUnitsCount() + 1;
                }
                // 拿到帐号
                if (danWeiInfo.getCity() == null) {
                    throw new BaseException("请填写所在城市");
                }
                String codeByName = CityCodeEnum.getCodeByName(danWeiInfo.getCity());
                if (codeByName == null) {
                    throw new BaseException("请填写正确的所在城市");
                }
                String account = codeByName + start;

                PacDanwei pacDanwei = pacDanweiService.getOneByDanWeiNum(account);
                // 插入用户数据
                SysUser sysUser = new SysUser();
                if (danWeiInfo.getSex().equals("男")) {
                    sysUser.setSex("0");
                } else {
                    sysUser.setSex("1");
                }
                sysUser.setSex(danWeiInfo.getSex());
                // 密码姓名首字母小写@学号
                String firstLetterLowercase = getFirstLetterLowercase(danWeiInfo.getName());
                String password = firstLetterLowercase + "@" + account;
                sysUser.setPassword(SecurityUtils.encryptPassword(password));
                sysUser.setCreateBy(operName);
                sysUser.setUserName(account);
                sysUser.setNickName(danWeiInfo.getName());
                sysUser.setPhonenumber(danWeiInfo.getPhone());
                sysUser.setDeptId(103L);

                if(danWeiInfo.getSex().equals("男")){
                    sysUser.setAvatar("/profile/avatar/2025/07/10/teacherMan.jpg");
                }else{
                    sysUser.setAvatar("/profile/avatar/2025/07/10/teacherWoman.jpg");
                }

                // 插入单位信息
                PacDanwei importTeacher = new PacDanwei();

                if (pacDanwei != null) {
                    sysUser.setUserId(Long.valueOf(pacDanwei.getUserId()));
                    importTeacher.setId(pacDanwei.getId());
                }
                // 插入用户信息
                if (sysUser.getUserId() == null) {
                    userMapper.insertUser(sysUser);
                    // 插入老师角色信息
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(sysUser.getUserId());
                    sysUserRole.setRoleId(102L);
                    userRoleMapper.insertUserRole(sysUserRole);
                } else {
                    userMapper.updateUser(sysUser);
                }
                importTeacher.setUserId(sysUser.getUserId().intValue());
                importTeacher.setName(danWeiInfo.getName());
                importTeacher.setDanWeiNum(account);
                importTeacher.setBirth(danWeiInfo.getBirth());
                importTeacher.setDuty(danWeiInfo.getDuty());
                importTeacher.setUnit(danWeiInfo.getUnit());
                importTeacher.setPhone(danWeiInfo.getPhone());
                importTeacher.setCity(danWeiInfo.getCity());
                // 插入老师信息
                pacDanweiService.saveOrUpdate(importTeacher);

                pacActivationStatus.setActivatedUnitsCount(start);
                pacActivationStatusService.updateById(pacActivationStatus);
                successNum++;
                successMsg.append("<br/>" + successNum + "姓名 " + importTeacher.getName() + "工号号 " + importTeacher.getDanWeiNum() + " 导入成功");

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "姓名 " + danWeiInfo.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    public static String extractCity(String address) {
        if (address == null || address.isEmpty()) return null;

        // 使用NLP分词器处理地址
        List<Term> termList = NLPTokenizer.segment(address);

        // 查找第一个"ns"词性（地名）
        for (Term term : termList) {
            if ("ns".equals(term.nature.toString())) {
                // 提取城市名（根据实际情况调整逻辑）
                String word = term.word;
                if (word.endsWith("市")) {
                    return word;
                } else if (word.endsWith("区") || word.endsWith("县")) {
                    // 可以进一步处理区/县所属的城市
                    // 此处简化处理，实际应用中可结合行政区域数据
                    return null;
                }
            }
        }

        return null;
    }

    public static String getFirstLetterLowercase(String chineseName) {
        if (chineseName == null || chineseName.isEmpty()) {
            return chineseName;
        }
        // 取首字母
        char firstChar = chineseName.charAt(0);

        String firstName = Character.toString(firstChar);
        // 判断是否为中文字符
        List<Pinyin> pinyins = PinyinDictionary.convertToPinyin(firstName);
        Pinyin pinyin = pinyins.get(0);
        char firstChar1 = pinyin.getFirstChar();
        return Character.toString(firstChar1).toLowerCase();
    }
}
